package com.alibaba.otter.canal.extend.autoconfigure;

import com.alibaba.otter.canal.extend.communication.CanalCommunicationClient;
import com.alibaba.otter.canal.extend.communication.CanalConfigClient;
import com.alibaba.otter.shared.communication.core.CommunicationClient;
import com.alibaba.otter.shared.communication.core.impl.DefaultCommunicationClientImpl;
import com.alibaba.otter.shared.communication.core.impl.dubbo.DubboCommunicationConnectionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration(proxyBeanMethods = false)
public class CanalAutoConfiguration {


    @Bean(initMethod = "initial", destroyMethod = "destroy")
    public CommunicationClient canalCommunicationClientDelegate(
            @Value("${otter.communication.payload:8388608}") Integer payload,
            @Value("${otter.communication.pool-size:10}") Integer poolSize) {

        DefaultCommunicationClientImpl communicationClient = new DefaultCommunicationClientImpl();
        // 设置连接方式
        DubboCommunicationConnectionFactory dubboCommunicationConnectionFactory = new DubboCommunicationConnectionFactory();
        dubboCommunicationConnectionFactory.setPayload(payload);
        // 设置dubbo通讯方式
        communicationClient.setFactory(dubboCommunicationConnectionFactory);
        communicationClient.setPoolSize(poolSize);
        return communicationClient;
    }

    @Bean
    public CanalCommunicationClient canalCommunicationClient(
            @Value("${otter.manager.address:127.0.0.1:1099}") String address,
            @Qualifier("canalCommunicationClientDelegate") CommunicationClient canalCommunicationClientDelegate) {

        CanalCommunicationClient canalCommunicationClient = new CanalCommunicationClient();
        canalCommunicationClient.setManagerAddress(address);
        canalCommunicationClient.setDelegate(canalCommunicationClientDelegate);
        return canalCommunicationClient;
    }

    @Bean
    public CanalConfigClient canalConfigClient(CanalCommunicationClient canalCommunicationClient) {

        CanalConfigClient canalConfigClient = new CanalConfigClient();
        canalConfigClient.setDelegate(canalCommunicationClient);
        return canalConfigClient;
    }
}
